<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="基于Go的Rabbitmq实践, 双的鱼 双的鱼博客 hexo博客 个人博客">
    <meta name="description" content="双的鱼博客，记录我的学习和感想">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>基于Go的Rabbitmq实践 | 双的鱼博客</title>
    <link rel="icon" type="image/png" href="/images/logo.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="双的鱼博客" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/images/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">双的鱼博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/weibo" class="waves-effect waves-light">
      
      <i class="fa fa-comment" style="zoom: 0.6;"></i>
      
      <span>微博</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/album" class="waves-effect waves-light">
      
      <i class="fa fa-camera-retro" style="zoom: 0.6;"></i>
      
      <span>相册</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/images/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">双的鱼博客</div>
        <div class="logo-desc">
            
            双的鱼博客，记录我的学习和感想
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/weibo" class="waves-effect waves-light">
			
			    <i class="fa-fw fa fa-comment"></i>
			
			微博
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/album" class="waves-effect waves-light">
			
			    <i class="fa-fw fa fa-camera-retro"></i>
			
			相册
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/gallery/rabbitmq.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">基于Go的Rabbitmq实践</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
        height: auto;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
        max-height: calc(100vh - 10rem);
    }

    #toc-content ol {
        padding-left: 10px;
        overflow: auto;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Go/">
                                <span class="chip bg-color">Go</span>
                            </a>
                        
                            <a href="/tags/Rabbitmq/">
                                <span class="chip bg-color">Rabbitmq</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%8A%80%E6%9C%AF/" class="post-category">
                                技术
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-16
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    14 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>学会使用消息队列是后端程序员进阶的必备技能之一，消息队列可以异步处理请求，缓解系统的压力，从而达到解耦、削峰等目的，大大提高系统的可用性以及扩展性。</p>
</blockquote>
<p>Rabbitmq是使用Erlang语言实现AMQP协议的消息中间件，具有易用、高扩展、高可用、持久化等方面特点，由于成熟优秀的表现和拥有活跃的文档跟社区，Rabbitmq成为很多人开发消息队列的首选。</p>
<h2 id="环境安装"><a href="#环境安装" class="headerlink" title="环境安装"></a>环境安装</h2><p>参考<a target="_blank" rel="noopener" href="https://blog.csdn.net/u013219624/article/details/83412925">https://blog.csdn.net/u013219624/article/details/83412925</a></p>
<h3 id="1、安装erlang"><a href="#1、安装erlang" class="headerlink" title="1、安装erlang"></a>1、安装erlang</h3><p>由于是基于Erlang开发的，所以必须先安装Erlang环境，从<a target="_blank" rel="noopener" href="http://www.erlang.org/downloads">官网</a>可以看到安装源码包，使用wget下载的话会很慢，推荐使用三方下载器下载，然后通过ssh工具传到服务器上，我的软件下载目录一般是 <code>/usr/local/</code>，这里就安装在 /usr/local/erlang。</p>
<p>然后解压安装包，安装。</p>
<pre class="language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># wget http://erlang.org/download/otp_src_21.3.tar.gz</span>
<span class="token comment"># tar -xvzf otp_src_21.3.tar.gz</span>
<span class="token comment"># cd otp_src_21.3</span>
<span class="token comment"># ./configure --prefix=/usr/local/erlang --without-javac</span>
<span class="token comment"># make &amp;&amp; make install</span></code></pre>

<p>验证一下是否安装成功，切换到 /usr/local/erlang目录，执行下方指令即可看到。</p>
<pre class="language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># bin/erl</span></code></pre>

<p>别忘了配置环境变量，打开 <code>/etc/profile</code> 进行如下编辑</p>
<pre class="language-bash" data-language="bash"><code class="language-bash"><span class="token builtin class-name">export</span> <span class="token assign-left variable">ERLPATH</span><span class="token operator">=</span>/usr/local/erlang
<span class="token builtin class-name">export</span> <span class="token assign-left variable"><span class="token environment constant">PATH</span></span><span class="token operator">=</span><span class="token environment constant">$PATH</span><span class="token builtin class-name">:</span><span class="token variable">$ERLPATH</span>/bin</code></pre>

<p>修改好之后重新生效配置</p>
<pre class="language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># source /etc/profile</span></code></pre>

<p>现在可以直接用 <code># erl</code> 指令运行erlang了。</p>
<h3 id="2-安装Rabbitmq"><a href="#2-安装Rabbitmq" class="headerlink" title="2.安装Rabbitmq"></a>2.安装Rabbitmq</h3><p>Rabitmq安装比较省力，从官方提供的<a target="_blank" rel="noopener" href="https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.15/">下载地址</a>中下载rpm安装包，直接安装即可。</p>
<pre class="language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># wget https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.15/rabbitmq-server-3.6.15-1.el7.noarch.rpm</span>
<span class="token comment"># yum -y install rabbitmq-server-3.6.15-1.el7.noarch.rpm</span></code></pre>

<p>查看是否安装成功，首先启动服务，然后查看服务状态。</p>
<pre class="language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># service rabbitmq-server start</span>
<span class="token comment"># service rabbitmq-server status</span></code></pre>

<p>以下是Rabbitmq其它常用指令：</p>
<pre class="language-bash" data-language="bash"><code class="language-bash">// 停止服务
<span class="token comment"># service rabbitmq-server stop</span>
// 重启服务
<span class="token comment"># service rabbitmq-server restart</span>
// 设置开机启动
<span class="token comment"># chkconfig rabbitmq-server on</span>
// 启动web管理插件<span class="token punctuation">(</span><span class="token number">127.0</span>.0.1:15672<span class="token punctuation">)</span>
<span class="token comment"># rabbitmq-plugins enable rabbitmq_management</span>
// 查看用户列表
<span class="token comment"># rabbitmqctl list_users</span>
// 添加用户
<span class="token comment"># rabbitmqctl add_user admin 123456</span>
// 设置用户角色
<span class="token comment"># rabbitmqctl set_user_tags admin administrator</span>
// 设置权限
<span class="token comment"># rabbitmqctl set_permissions -p / admin ".*" ".*" ".*"</span>
// 删除用户
<span class="token comment"># rabbitmqctl delete_user admin</span>
// 修改用户密码
<span class="token comment"># rabbitmqctl change_password admin 123456</span></code></pre>

<p>默认的用户密码是 guest guest，但只限本地访问，远程访问的话必须先创建一个新用户，指定为管理员角色，分配管理员权限，就可以登录管理后台进行操作了。</p>
<p>下图就是登录后的管理界面，这上面可以看到节点、端口、交换机、队列等信息，还可以手动发送消息，管理消息，十分方便。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/716745-20fb0445a558495e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<h2 id="名词解释"><a href="#名词解释" class="headerlink" title="名词解释"></a>名词解释</h2><h3 id="1、基础模块"><a href="#1、基础模块" class="headerlink" title="1、基础模块"></a>1、基础模块</h3><p>要熟练使用Rabbitmq就必须知道其名词含义和工作机制</p>
<blockquote>
<p>基本流程</p>
</blockquote>
<p>基本的工作流程是这样的：生产者，就是你的发送程序，通过TCP连接，创建channel(通道)向指定的exchange(交换机)发送一个消息，exchange再将消息下发到binding(绑定)的queue(队列)中，然后消费者(处理程序)监听接收queue中的消息进行处理。</p>
<p>这是google的一张流程图</p>
<p><img src="https://upload-images.jianshu.io/upload_images/716745-879fc1f697a02944.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<blockquote>
<p>生产者，消费者</p>
</blockquote>
<p>即发送消息和接收处理消息的逻辑程序</p>
<blockquote>
<p>Channel</p>
</blockquote>
<p>通道，rabbitmq的本质是tcp通信，利用tcp连接创建内部的逻辑连接，注意，此通道不是tcp本身通道(tcp一个连接就是一个通道)，而是共享一个tcp连接的其内部实现的连接，至于rabbitmq内部如何实现的我也没吃透，应该是用到了多路复用，总之rabbitmq一切收发都是通过channel实现的，避免了重复连接tcp产生的资源消耗。</p>
<blockquote>
<p>Exchange</p>
</blockquote>
<p>交换机，相当于是一个消息中转控制中心，负责接收消息然后根据路由规则将消息下发到指定的queue。</p>
<blockquote>
<p>Queue</p>
</blockquote>
<p>队列，即存放消息的地方，消费的时候直接从队列里取。</p>
<h3 id="2、参数说明"><a href="#2、参数说明" class="headerlink" title="2、参数说明"></a>2、参数说明</h3><blockquote>
<p>Routing Key</p>
</blockquote>
<p>路由键，是exchange跟queue之间的桥梁，exchange根据绑定的routing key下发消息到对应的queue中，决定了消息的流向，键名可以自定义。</p>
<blockquote>
<p>Type</p>
</blockquote>
<p>exchange的类型，有’fanout’、’direct’、’topic’、’headers’四个类型。</p>
<ul>
<li><strong>fanout</strong>：不需要指定路由键，直接将消息发送给exchange中的所有queue，类似于广播。</li>
<li><strong>direct</strong>：将消息发给exchange中指定路由键的queue中，相当于精准投放。</li>
<li><strong>topic</strong>：匹配模式，消息下发到匹配规则的routing key的queue中，有’*‘与’#’两个通配符，’*‘表示只匹配一个词，’#’表示匹配多个，比如’user.*‘只能匹配到’user.name’而不能匹配到’user.name.wang’，’user.#’则都可以匹配到。</li>
<li><strong>headers</strong>：根据消息体的headers匹配，这种用到的比较少，绑定的时候指定相关header参数即可。</li>
</ul>
<blockquote>
<p>Durable</p>
</blockquote>
<p>exchange跟queue都有这个参数，类型为boolean，表示是否持久化。</p>
<blockquote>
<p>Auto delete</p>
</blockquote>
<p>exchange跟queue都有这个参数，类型为boolean，我试了一下，当exchange绑定的queue全都解绑的时候exchange会自动删除，queue好像没什么影响。</p>
<blockquote>
<p>Internal</p>
</blockquote>
<p>exchange有这个参数，类型为boolean，内部的，意味着不能对这个exchange发送消息，通过管理后台还是可以发送消息的。</p>
<blockquote>
<p>noWait</p>
</blockquote>
<p>几乎每个步骤都有这个参数，类型为boolean，不需要服务器任何返回值的意思，指服务端创建队列发送消息等，rabbitmq不需要这个返回状态即可进行下一步，正常来说不会用到这个参数，容易报异常。</p>
<blockquote>
<p>Exclusive</p>
</blockquote>
<p>queue有这个参数，类型为boolean，排他队列，只对创建该队列的用户可见，其它用户无法访问。</p>
<blockquote>
<p>延伸扩展</p>
</blockquote>
<p>rabbitmq还提供了很多扩展参数，比如’x-message-ttl’给消息设置过时时间，’x-max-length-bytes’设置消息最大长度，’x-dead-letter-exchange’设置消息过时后推送到的exchange等等，具体的官方文档也提供了，也可以看管理后台创建exchange、queue的时候会有提示的额外参数。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/716745-37258e22a0f6014b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<h2 id="编程实践"><a href="#编程实践" class="headerlink" title="编程实践"></a>编程实践</h2><p>使用Go语言操作Rabbitmq需要用到这个库：<a target="_blank" rel="noopener" href="https://github.com/streadway/amqp">https://github.com/streadway/amqp</a>，这是一个带Rabbitmq扩展的AMQP客户端。</p>
<p>下面就一步步解析下基于go的rabbitmq收发过程。</p>
<h3 id="1、建立连接"><a href="#1、建立连接" class="headerlink" title="1、建立连接"></a>1、建立连接</h3><p>上面已经说过了，其本质是tcp链接，并且是基于内部通道进行的通信，所以一个完整的连接分为连接与创建通道两部分。</p>
<p>连接地址的格式是这种形式：<em>amqp://admin:<a href="mailto:&#x31;&#50;&#51;&#52;&#53;&#x36;&#64;&#x31;&#x32;&#x37;&#x2e;&#x30;&#46;&#48;&#x2e;&#x31;">&#x31;&#50;&#51;&#52;&#53;&#x36;&#64;&#x31;&#x32;&#x37;&#x2e;&#x30;&#46;&#48;&#x2e;&#x31;</a>:5672/</em></p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token comment">// 建立连接</span>
connection<span class="token punctuation">,</span> err <span class="token operator">:=</span> amqp<span class="token punctuation">.</span><span class="token function">Dial</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to connect to RabbitMQ:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span>
<span class="token keyword">defer</span> connection<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment">// 创建一个Channel</span>
channel<span class="token punctuation">,</span> err <span class="token operator">:=</span> connection<span class="token punctuation">.</span><span class="token function">Channel</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to open a channel:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span>
<span class="token keyword">defer</span> channel<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>

<h3 id="2、声明exchange"><a href="#2、声明exchange" class="headerlink" title="2、声明exchange"></a>2、声明exchange</h3><p>首先声明需要发送到的exchange，如果此exchange不存在将会被自动创建。</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token comment">// 声明 exchange</span>
<span class="token keyword">if</span> err <span class="token operator">:=</span> channel<span class="token punctuation">.</span><span class="token function">ExchangeDeclare</span><span class="token punctuation">(</span>
	exchange<span class="token punctuation">,</span> <span class="token comment">//name</span>
	<span class="token string">"direct"</span><span class="token punctuation">,</span> <span class="token comment">//exchangeType</span>
	<span class="token boolean">true</span><span class="token punctuation">,</span>     <span class="token comment">//durable</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>    <span class="token comment">//auto-deleted</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>    <span class="token comment">//internal</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>    <span class="token comment">//noWait</span>
	<span class="token boolean">nil</span><span class="token punctuation">,</span>      <span class="token comment">//arguments</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to declare a exchange:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span></code></pre>

<p>这里声明的exchange类型为’direct’，精准投放模式，持久化，这也是最常用的配置。</p>
<h3 id="3、声明queue"><a href="#3、声明queue" class="headerlink" title="3、声明queue"></a>3、声明queue</h3><p>同样，queue也需要先声明，不存在的也会被自动创建。</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token comment">// 声明一个queue</span>
<span class="token keyword">if</span> <span class="token boolean">_</span><span class="token punctuation">,</span> err <span class="token operator">:=</span> channel<span class="token punctuation">.</span><span class="token function">QueueDeclare</span><span class="token punctuation">(</span>
	queue<span class="token punctuation">,</span> <span class="token comment">// name</span>
	<span class="token boolean">true</span><span class="token punctuation">,</span>  <span class="token comment">// durable</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// delete when unused</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// exclusive</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// no-wait</span>
	<span class="token boolean">nil</span><span class="token punctuation">,</span>   <span class="token comment">// arguments</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to declare a queue:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span></code></pre>

<p>此队列为持久化队列，以上也是最常用的配置。</p>
<h3 id="4、绑定queue"><a href="#4、绑定queue" class="headerlink" title="4、绑定queue"></a>4、绑定queue</h3><p>创建好exchange和queue之后，需要建立两者的联系，即绑定，第二个参数就是指定的 routing_key。</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token comment">// exchange 绑定 queue</span>
channel<span class="token punctuation">.</span><span class="token function">QueueBind</span><span class="token punctuation">(</span>queue<span class="token punctuation">,</span> routing_key<span class="token punctuation">,</span> exchange<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span></code></pre>

<h3 id="5、发送消息"><a href="#5、发送消息" class="headerlink" title="5、发送消息"></a>5、发送消息</h3><p>万事俱备，只剩发送了，指定需要发送的exchange跟’routing_key’，设置好发送的消息体就可以将消息发送出去了，为什么不用指定queue呢，因为消息是先投放到exchange的，exchange会自动根据绑定的规则将消息下发到对应的queue。</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token comment">// 发送</span>
messageBody <span class="token operator">:=</span> comhelper<span class="token punctuation">.</span><span class="token function">JsonEncode</span><span class="token punctuation">(</span>content<span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">=</span> channel<span class="token punctuation">.</span><span class="token function">Publish</span><span class="token punctuation">(</span>
	exchange<span class="token punctuation">,</span>    <span class="token comment">// exchange</span>
	routing_key<span class="token punctuation">,</span> <span class="token comment">// routing key</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>       <span class="token comment">// mandatory</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>       <span class="token comment">// immediate</span>
	amqp<span class="token punctuation">.</span>Publishing<span class="token punctuation">&#123;</span>
		Headers<span class="token punctuation">:</span>         amqp<span class="token punctuation">.</span>Table<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
		ContentType<span class="token punctuation">:</span>     <span class="token string">"text/plain"</span><span class="token punctuation">,</span>
		ContentEncoding<span class="token punctuation">:</span> <span class="token string">""</span><span class="token punctuation">,</span>
		Body<span class="token punctuation">:</span>            <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span>messageBody<span class="token punctuation">)</span><span class="token punctuation">,</span>
		<span class="token comment">//Expiration:      "60000", // 消息过期时间</span>
	<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to publish a message:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span></code></pre>

<p>消息体的设置可以去程序中看’Publishing’的定义，有优先级、过期时间等诸多设置。</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Publishing <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	<span class="token comment">// Application or exchange specific fields,</span>
	<span class="token comment">// the headers exchange will inspect this field.</span>
	Headers Table

	<span class="token comment">// Properties</span>
	ContentType     <span class="token builtin">string</span>    <span class="token comment">// MIME content type</span>
	ContentEncoding <span class="token builtin">string</span>    <span class="token comment">// MIME content encoding</span>
	DeliveryMode    <span class="token builtin">uint8</span>     <span class="token comment">// Transient (0 or 1) or Persistent (2)</span>
	Priority        <span class="token builtin">uint8</span>     <span class="token comment">// 0 to 9</span>
	CorrelationId   <span class="token builtin">string</span>    <span class="token comment">// correlation identifier</span>
	ReplyTo         <span class="token builtin">string</span>    <span class="token comment">// address to to reply to (ex: RPC)</span>
	Expiration      <span class="token builtin">string</span>    <span class="token comment">// message expiration spec</span>
	MessageId       <span class="token builtin">string</span>    <span class="token comment">// message identifier</span>
	Timestamp       time<span class="token punctuation">.</span>Time <span class="token comment">// message timestamp</span>
	Type            <span class="token builtin">string</span>    <span class="token comment">// message type name</span>
	UserId          <span class="token builtin">string</span>    <span class="token comment">// creating user id - ex: "guest"</span>
	AppId           <span class="token builtin">string</span>    <span class="token comment">// creating application id</span>

	<span class="token comment">// The application specific payload of the message</span>
	Body <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span>
<span class="token punctuation">&#125;</span></code></pre>

<p>运行程序，发送一条消息，我们可以通过管理后台看到发送的消息，这时候登录管理控制台，会发现exchange、queue以及绑定关系都被自动创建了。</p>
<p>来到’Queues’面板，找到下面的’Get messages’，点击按钮就能看到消息了。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/716745-2320b834beaec71b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<h3 id="6、消费消息"><a href="#6、消费消息" class="headerlink" title="6、消费消息"></a>6、消费消息</h3><p>消息的消费也是从连接并且创建通道开始的，不过消费者不需要声明exchange，因为它是直接从queue中取消息的，所以只声明一个queue即可，注意配置需要跟生产者一样。</p>
<p>其核心代码是注册消费者。</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token comment">// 注册消费者</span>
msgs<span class="token punctuation">,</span> err <span class="token operator">:=</span> ch<span class="token punctuation">.</span><span class="token function">Consume</span><span class="token punctuation">(</span>
	q<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> <span class="token comment">// queue</span>
	<span class="token string">"project"</span><span class="token punctuation">,</span> <span class="token comment">// 标签</span>
	<span class="token boolean">true</span><span class="token punctuation">,</span>   <span class="token comment">// auto-ack</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>  <span class="token comment">// exclusive</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>  <span class="token comment">// no-local</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span>  <span class="token comment">// no-wait</span>
	<span class="token boolean">nil</span><span class="token punctuation">,</span>    <span class="token comment">// args</span>
<span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to register a consumer:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span></code></pre>

<p>同样我们也可以在管理控制台的当前queue面板中看到’Consumers’信息。</p>
<h3 id="7、完整代码"><a href="#7、完整代码" class="headerlink" title="7、完整代码"></a>7、完整代码</h3><p>生产者</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"github.com/streadway/amqp"</span>
	<span class="token string">"helper_go/comhelper"</span>
	<span class="token string">"log"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	uri <span class="token operator">:=</span> <span class="token string">"amqp://admin:123456@127.0.0.1:5672/"</span>
	exchange <span class="token operator">:=</span> <span class="token string">"project"</span>
	queue <span class="token operator">:=</span> <span class="token string">"pj_event"</span>
	routing_key <span class="token operator">:=</span> <span class="token string">"pj_event"</span>
	content <span class="token operator">:=</span> <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span>
		<span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"zelda"</span><span class="token punctuation">,</span>
	<span class="token punctuation">&#125;</span>

	err <span class="token operator">:=</span> <span class="token function">Pub_mq</span><span class="token punctuation">(</span>uri<span class="token punctuation">,</span> exchange<span class="token punctuation">,</span> queue<span class="token punctuation">,</span> routing_key<span class="token punctuation">,</span> content<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 生产者</span>
<span class="token keyword">func</span> <span class="token function">Pub_mq</span><span class="token punctuation">(</span>uri<span class="token punctuation">,</span> exchange<span class="token punctuation">,</span> queue<span class="token punctuation">,</span> routing_key <span class="token builtin">string</span><span class="token punctuation">,</span> content <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	<span class="token comment">// 建立连接</span>
	connection<span class="token punctuation">,</span> err <span class="token operator">:=</span> amqp<span class="token punctuation">.</span><span class="token function">Dial</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to connect to RabbitMQ:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">defer</span> connection<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token comment">// 创建一个Channel</span>
	channel<span class="token punctuation">,</span> err <span class="token operator">:=</span> connection<span class="token punctuation">.</span><span class="token function">Channel</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to open a channel:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">defer</span> channel<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token comment">// 声明exchange</span>
	<span class="token keyword">if</span> err <span class="token operator">:=</span> channel<span class="token punctuation">.</span><span class="token function">ExchangeDeclare</span><span class="token punctuation">(</span>
		exchange<span class="token punctuation">,</span> <span class="token comment">//name</span>
		<span class="token string">"direct"</span><span class="token punctuation">,</span> <span class="token comment">//exchangeType</span>
		<span class="token boolean">true</span><span class="token punctuation">,</span>     <span class="token comment">//durable</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>    <span class="token comment">//auto-deleted</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>    <span class="token comment">//internal</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>    <span class="token comment">//noWait</span>
		<span class="token boolean">nil</span><span class="token punctuation">,</span>      <span class="token comment">//arguments</span>
	<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to declare a exchange:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>
	<span class="token comment">// 声明一个queue</span>
	<span class="token keyword">if</span> <span class="token boolean">_</span><span class="token punctuation">,</span> err <span class="token operator">:=</span> channel<span class="token punctuation">.</span><span class="token function">QueueDeclare</span><span class="token punctuation">(</span>
		queue<span class="token punctuation">,</span> <span class="token comment">// name</span>
		<span class="token boolean">true</span><span class="token punctuation">,</span>  <span class="token comment">// durable</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// delete when unused</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// exclusive</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// no-wait</span>
		<span class="token boolean">nil</span><span class="token punctuation">,</span>   <span class="token comment">// arguments</span>
	<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to declare a queue:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>
	<span class="token comment">// exchange 绑定 queue</span>
	channel<span class="token punctuation">.</span><span class="token function">QueueBind</span><span class="token punctuation">(</span>queue<span class="token punctuation">,</span> routing_key<span class="token punctuation">,</span> exchange<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>

	<span class="token comment">// 发送</span>
	messageBody <span class="token operator">:=</span> comhelper<span class="token punctuation">.</span><span class="token function">JsonEncode</span><span class="token punctuation">(</span>content<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">=</span> channel<span class="token punctuation">.</span><span class="token function">Publish</span><span class="token punctuation">(</span>
		exchange<span class="token punctuation">,</span>    <span class="token comment">// exchange</span>
		routing_key<span class="token punctuation">,</span> <span class="token comment">// routing key</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>       <span class="token comment">// mandatory</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>       <span class="token comment">// immediate</span>
		amqp<span class="token punctuation">.</span>Publishing<span class="token punctuation">&#123;</span>
			Headers<span class="token punctuation">:</span>         amqp<span class="token punctuation">.</span>Table<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
			ContentType<span class="token punctuation">:</span>     <span class="token string">"text/plain"</span><span class="token punctuation">,</span>
			ContentEncoding<span class="token punctuation">:</span> <span class="token string">""</span><span class="token punctuation">,</span>
			Body<span class="token punctuation">:</span>            <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span>messageBody<span class="token punctuation">)</span><span class="token punctuation">,</span>
			<span class="token comment">//Expiration:      "60000", // 消息过期时间</span>
		<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
	<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to publish a message:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span>
</code></pre>

<p>消费者</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">"fmt"</span>
	<span class="token string">"github.com/streadway/amqp"</span>
	<span class="token string">"log"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	uri <span class="token operator">:=</span> <span class="token string">"amqp://admin:123456@127.0.0.1:5672/"</span>
	exchange <span class="token operator">:=</span> <span class="token string">"project"</span>
	queue <span class="token operator">:=</span> <span class="token string">"pj_event"</span>

	err <span class="token operator">:=</span> <span class="token function">Use_mq</span><span class="token punctuation">(</span>uri<span class="token punctuation">,</span> exchange<span class="token punctuation">,</span> queue<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 消费者</span>
<span class="token keyword">func</span> <span class="token function">Use_mq</span><span class="token punctuation">(</span>uri<span class="token punctuation">,</span> exchange<span class="token punctuation">,</span> queue <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	<span class="token comment">// 建立连接</span>
	conn<span class="token punctuation">,</span> err <span class="token operator">:=</span> amqp<span class="token punctuation">.</span><span class="token function">Dial</span><span class="token punctuation">(</span>uri<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to connect to RabbitMQ:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">defer</span> conn<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token comment">// 启动一个通道</span>
	ch<span class="token punctuation">,</span> err <span class="token operator">:=</span> conn<span class="token punctuation">.</span><span class="token function">Channel</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to open a channel:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>

	<span class="token comment">// 声明一个队列</span>
	q<span class="token punctuation">,</span> err <span class="token operator">:=</span> ch<span class="token punctuation">.</span><span class="token function">QueueDeclare</span><span class="token punctuation">(</span>
		queue<span class="token punctuation">,</span> <span class="token comment">// name</span>
		<span class="token boolean">true</span><span class="token punctuation">,</span>  <span class="token comment">// durable</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// delete when usused</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// exclusive</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// no-wait</span>
		<span class="token boolean">nil</span><span class="token punctuation">,</span>   <span class="token comment">// arguments</span>
	<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to declare a queue:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>
	<span class="token comment">// 注册消费者</span>
	msgs<span class="token punctuation">,</span> err <span class="token operator">:=</span> ch<span class="token punctuation">.</span><span class="token function">Consume</span><span class="token punctuation">(</span>
		q<span class="token punctuation">.</span>Name<span class="token punctuation">,</span>    <span class="token comment">// queue</span>
		<span class="token string">"project"</span><span class="token punctuation">,</span> <span class="token comment">// 标签</span>
		<span class="token boolean">true</span><span class="token punctuation">,</span>      <span class="token comment">// auto-ack</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>     <span class="token comment">// exclusive</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>     <span class="token comment">// no-local</span>
		<span class="token boolean">false</span><span class="token punctuation">,</span>     <span class="token comment">// no-wait</span>
		<span class="token boolean">nil</span><span class="token punctuation">,</span>       <span class="token comment">// args</span>
	<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to register a consumer:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">&#125;</span>

	forever <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token keyword">chan</span> <span class="token builtin">bool</span><span class="token punctuation">)</span>
	<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">for</span> d <span class="token operator">:=</span> <span class="token keyword">range</span> msgs <span class="token punctuation">&#123;</span>
			log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>d<span class="token punctuation">.</span>Type<span class="token punctuation">)</span>
			log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>d<span class="token punctuation">.</span>MessageId<span class="token punctuation">)</span>
			log<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"Received a message: %s"</span><span class="token punctuation">,</span> d<span class="token punctuation">.</span>Body<span class="token punctuation">)</span>
		<span class="token punctuation">&#125;</span>
	<span class="token punctuation">&#125;</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	log<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"Waiting for messages. To exit press CTRL+C"</span><span class="token punctuation">)</span>
	<span class="token operator">&lt;-</span>forever

	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">&#125;</span>
</code></pre>

<h2 id="高级应用"><a href="#高级应用" class="headerlink" title="高级应用"></a>高级应用</h2><p>现在我们有一个需求，要求给消息设置过期时间，过期的消息放到另一个队列进行额外的处理，这个队列就叫死信队列。</p>
<p>先来看消息过期时间的设置，有两种方法，一种是声明队列的时候设置<code>x-message-ttl</code>参数，这样这个队列中的消息都会有一个过期时间；还有一种就是发送消息的时候单独给这条消息设置过期时间，即<code>Expiration</code>参数，如果两个参数都设置了，那么以时间短的那个为准。</p>
<p>来做个准备工作，先删除之前创建的’pj_event’队列，然后再控制台手动创建一个名为’dead’的exchange，和一个名为’de_event’的队列，将两者绑定。</p>
<p>然后改造生产者声明queue的代码，如下：</p>
<pre class="language-go" data-language="go"><code class="language-go"><span class="token comment">// 声明一个queue</span>
args <span class="token operator">:=</span> amqp<span class="token punctuation">.</span>Table<span class="token punctuation">&#123;</span>
	<span class="token string">"x-message-ttl"</span><span class="token punctuation">:</span>             <span class="token function">int64</span><span class="token punctuation">(</span><span class="token number">60000</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
	<span class="token string">"x-dead-letter-exchange"</span><span class="token punctuation">:</span>    <span class="token string">"dead"</span><span class="token punctuation">,</span>
	<span class="token string">"x-dead-letter-routing-key"</span><span class="token punctuation">:</span> <span class="token string">""</span><span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">if</span> <span class="token boolean">_</span><span class="token punctuation">,</span> err <span class="token operator">:=</span> channel<span class="token punctuation">.</span><span class="token function">QueueDeclare</span><span class="token punctuation">(</span>
	queue<span class="token punctuation">,</span> <span class="token comment">// name</span>
	<span class="token boolean">true</span><span class="token punctuation">,</span>  <span class="token comment">// durable</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// delete when unused</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// exclusive</span>
	<span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token comment">// no-wait</span>
	args<span class="token punctuation">,</span>  <span class="token comment">// arguments</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
	log<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Failed to declare a queue:"</span><span class="token punctuation">,</span> err<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> err
<span class="token punctuation">&#125;</span></code></pre>

<p>其中<code>x-message-ttl</code>参数设置过期时间，必须是int64格式，<code>x-dead-letter-exchange</code>设置消息过期后下发的交换机，<code>x-dead-letter-routing-key</code>参数必须指定，如果私信队列绑定的时候没有routing key为空就好。</p>
<p>运行代码，从控制台可以看到两条队列的消息情况。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/716745-17c3a1985ca190cf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<p>可以看到’pj_event’的消息条数为1，’de_event’死信队列的消息为0，静待一分钟之后再次观察。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/716745-c16dbc5e1247e640.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<p>这时候’pj_event’中已经没有消息了，而’de_event’中多出了一条消息，点进’de_event’，查看具体的消息内容。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/716745-d4cc62ec0cb5beaa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"></p>
<p>可以看到消息的内容以及来源。</p>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>Rabbitmq的介绍告一段落，通过本教程相信应该可以领大家入门了，更多的功能我也在研究中，总之，学会使用队列是后端程序员进阶的必备知识，可一定要掌握呀。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">JIANG XIAOFAN</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://shuangdeyu.gitee.io/2019/04/16/ji-yu-go-de-rabbitmq-shi-jian/">https://shuangdeyu.gitee.io/2019/04/16/ji-yu-go-de-rabbitmq-shi-jian/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">JIANG XIAOFAN</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Go/">
                                    <span class="chip bg-color">Go</span>
                                </a>
                            
                                <a href="/tags/Rabbitmq/">
                                    <span class="chip bg-color">Rabbitmq</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg4.jpeg") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'Cu0yGDQXYEoC2BMFqoMyqSK1-gzGzoHsz',
        appKey: 'PYfyCYN5lI59X5Rczd5IGls5',
        notify: 'false' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '20',
        lang: 'zh-cn',
        placeholder: 'hi，留个脚印吧'
    });
</script>

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/05/24/sai-er-da-mei-tu-xin-shang.yi/">
                    <div class="card-image">
                        
                        <img src="/gallery/saierda.jpg" class="responsive-img" alt="塞尔达美图欣赏.一">
                        
                        <span class="card-title">塞尔达美图欣赏.一</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-05-24
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%B8%B8%E6%88%8F/" class="post-category">
                                    游戏
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Nintendo/">
                        <span class="chip bg-color">Nintendo</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/04/goquery-pa-chong-shi-jian-an-li/">
                    <div class="card-image">
                        
                        <img src="/gallery/goquery.png" class="responsive-img" alt="goquery爬虫实践案例">
                        
                        <span class="card-title">goquery爬虫实践案例</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-04-04
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF/" class="post-category">
                                    技术
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go/">
                        <span class="chip bg-color">Go</span>
                    </a>
                    
                    <a href="/tags/%E7%88%AC%E8%99%AB/">
                        <span class="chip bg-color">爬虫</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="113118807"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2024</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">JIANG XIAOFAN</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">107k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>















    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

	
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
